package com.ruoyi.pingan.fymodule.order.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.pingan.fymodule.order.entity.SxoSafetyOrder;
import com.ruoyi.pingan.fymodule.order.entity.SxoSafetyOrderDetail;
import com.ruoyi.pingan.fymodule.order.mapper.SxoSafetyOrderMapper;
import com.ruoyi.pingan.fymodule.order.service.*;
import com.ruoyi.pingan.fymodule.thirdpa.model.dto.BankClearQueryDto;
import com.ruoyi.pingan.fymodule.thirdpa.model.dto.SubsidyQuestDto;
import com.ruoyi.pingan.fymodule.thirdpa.model.dto.TraFinalStatusQueryDto;
import com.ruoyi.pingan.fymodule.thirdpa.model.vo.BankClearQueryVo;
import com.ruoyi.pingan.fymodule.thirdpa.model.vo.BankClearTranItemArrayVo;
import com.ruoyi.pingan.fymodule.thirdpa.model.vo.TraFinalStatusQueryVo;
import com.ruoyi.pingan.fymodule.thirdpa.service.PaOrderService;
import com.ruoyi.pingan.fymodule.thirdpa.service.impl.PaBondServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 *
 * 平安分账订单 业务层实现
 *
 * @author wangy
 * @since 2025-06-18
 */
@Slf4j
@Service
public class SxoSafetyOrderServiceImpl extends ServiceImpl<SxoSafetyOrderMapper, SxoSafetyOrder> implements ISxoSafetyOrderService {

    @Autowired
    private PaOrderService paOrderService;

    @Autowired
    private ISxoSafetyOrderDetailService sxoSafetyOrderDetailService;

    @Autowired
    private PaBondServiceImpl paBondService;

    @Autowired
    private ISxoSafetyOrderService sxoSafetyOrderService;


    @Override
    public void execute6273_6267() {
        log.info("冻结充值状态查询；时间:{}", DateUtil.now());
        Date date = new Date();
        Date startTime = DateUtil.offsetDay(date, -1);
        //Date endTime = DateUtil.offsetMinute(date, -120);
        LambdaQueryWrapper<SxoSafetyOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetyOrder::getOrdersStatus, 2);
        queryWrapper.eq(SxoSafetyOrder::getStatus, 0);
        queryWrapper.ge(SxoSafetyOrder::getPushTime, DateUtil.format(startTime, "yyyy-MM-dd").concat(" 00:00:00"));
        queryWrapper.le(SxoSafetyOrder::getPushTime,  DateUtil.now());
        queryWrapper.orderByAsc(SxoSafetyOrder::getId);
        List<SxoSafetyOrder> lists = this.list(queryWrapper);
        if (lists.isEmpty()) {
            log.info("结束冻结充值状态查询；时间:{};数量：{}", DateUtil.now(),0);
            return;
        }
        String dataStr = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
        for (SxoSafetyOrder sxoSafetyOrder : lists) {
            try {
                if (StrUtil.isEmpty(sxoSafetyOrder.getJzbAcceptSeqNo())) {
                    continue;
                }
                TraFinalStatusQueryDto dto = new TraFinalStatusQueryDto();
                dto.setOldJzbAcceptSeqNo(sxoSafetyOrder.getJzbAcceptSeqNo());
                TraFinalStatusQueryVo vo = paOrderService.traFinalStatusQuery(dto);
                //执行vo的存储
                //交易状态
                if (!"6267".equals(vo.getTranType())) {
                   continue;
                }
                //成功
                if ("0".equals(vo.getTranStatus())){
                    String tranDateStr = vo.getTranDate().concat(vo.getTranTime());
                    Date tranDate = DateUtil.parse(tranDateStr);
                    SxoSafetyOrder mod = new SxoSafetyOrder();
                    mod.setId(sxoSafetyOrder.getId());
                    mod.setOrdersStatus(0);
                    mod.setPushSuccTime(DateUtil.format(tranDate, "yyyy-MM-dd HH:mm:ss"));
                    mod.setUpdTime(dataStr);
                    this.updateById(mod);
                }
                //失败
                if ("1".equals(vo.getTranStatus())){
                    String tranDateStr = vo.getTranDate().concat(vo.getTranTime());
                    Date tranDate = DateUtil.parse(tranDateStr);
                    SxoSafetyOrder mod = new SxoSafetyOrder();
                    mod.setId(sxoSafetyOrder.getId());
                    mod.setOrdersStatus(-2);
                    mod.setUpdTime(dataStr);
                    mod.setErrorMsg(vo.getTranDealStatusDesc());
                    this.updateById(mod);
                }
                //申请补贴
                /*if (sxoSafetyOrder.getSubsidyStatus().equals(0) && StrUtil.isNotEmpty(sxoSafetyOrder.getPlatTotalAmt())) {
                    applySubsidy(sxoSafetyOrder);
                }*/
            }catch (Exception e){
                log.error("execute6273_6267执行异常：{}", e.getMessage());
            }

        }
        log.info("结束冻结充值状态查询；时间:{}；数量：{}", DateUtil.now(), lists.size());
    }


    /**
     * 每天执行前一天的在途清算查询
     */
    @Override
    public void execute6108() {

        BankClearQueryDto bankClearQueryDto = new BankClearQueryDto();
        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 获取当前日期的前一天
        LocalDate yesterday = today.minusDays(1);

        // 定义日期格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");


        // 将日期格式化为"yyyyMMdd"的格式
        String Date = yesterday.format(formatter);

        bankClearQueryDto.setStartDate(Date);
        bankClearQueryDto.setEndDate(Date);
        BankClearQueryVo bankClearQueryVo = paBondService.bankClearQuery(bankClearQueryDto);
        if(bankClearQueryVo!=null){
            List<BankClearTranItemArrayVo> lists = bankClearQueryVo.getTranItemArray();
            for(BankClearTranItemArrayVo bankClearTranItemArrayVo :lists){
                String clearingStatus = bankClearTranItemArrayVo.getClearingStatus();
                //0：成功，1：失败，2：异常 3:待处理
                   //执行清算成功记录分账启动的标识，也就是查询的日期
                    LambdaQueryWrapper<SxoSafetyOrder> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SxoSafetyOrder::getPayOrderDate, Date);
                    List<SxoSafetyOrder> safetyOrders = sxoSafetyOrderService.list(queryWrapper);
                    for(SxoSafetyOrder sxoSafetyOrder:safetyOrders){
                        sxoSafetyOrder.setClearStatus(clearingStatus);
                        SimpleDateFormat localFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String clearDate  = localFormatter.format(new Date());
                        sxoSafetyOrder.setClearTime(clearDate);
                        sxoSafetyOrderService.updateById(sxoSafetyOrder);
                    }
            }
        }

    }





    private void applySubsidy(SxoSafetyOrder sxoSafetyOrder) {
        BigDecimal platTotalAmt = new BigDecimal(sxoSafetyOrder.getPlatTotalAmt());
        if (platTotalAmt.compareTo(new BigDecimal("0")) <= 0) {
            return;
        }
        LambdaQueryWrapper<SxoSafetyOrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetyOrderDetail::getSafetyOrderId, sxoSafetyOrder.getId());
        List<SxoSafetyOrderDetail> orderDetails = sxoSafetyOrderDetailService.list(queryWrapper);
        if (orderDetails.isEmpty()) {
            return;
        }
        SxoSafetyOrderDetail orderDetail = orderDetails.get(0);
        SubsidyQuestDto dto = new SubsidyQuestDto();
        dto.setOrderId(sxoSafetyOrder.getOrderId());
        dto.setSubsidyAmt(sxoSafetyOrder.getPlatTotalAmt());
        dto.setSubsidyInSubAcctNo(orderDetail.getSubOrderFillSubAcctNo());
        paOrderService.subsidyQuest(dto);
    }

}